﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;

/// <summary>
/// Summary description for DatabaseAccess
/// </summary>
public class DatabaseAccess
{
    private SqlConnection conn;
    private SqlDataAdapter da;
    private DataSet ds;
    public static readonly DatabaseAccess dbac = new DatabaseAccess();
    public SqlConnection OpenConnection()
    {
        conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);
        try
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
                conn.Open(); 
            }
            else
            {
                conn.Open();
            }
        }
        catch
        {
            return null;
        }
        return conn;

    }
    public void CloseConnection(SqlConnection conn)
    {
        if (conn.State == ConnectionState.Open)
        {
            conn.Close();
            conn.Dispose();
        }
    }
    public bool executeUpdate(String sql, SqlParameter[] paramList)
    {
        //Open connection
        conn = OpenConnection();
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddRange(paramList);
        try
        {
            if (cmd.ExecuteNonQuery() <= 0)
                return false;
        }
        catch (SqlException)
        {
            return false;
        }
        CloseConnection(conn);
        return true;
    }
    public DataTable executeSelect(String sql, SqlParameter[] paramList)
    { 
        //Open connection
        conn = OpenConnection();
        ds = new DataSet();
        da = new SqlDataAdapter(sql,conn);
        da.SelectCommand.CommandType = CommandType.StoredProcedure;
        da.SelectCommand.Parameters.AddRange(paramList);

        da.Fill(ds);
        CloseConnection(conn);
        if (ds.Tables.Count == 0)
            return null;
        else
            return ds.Tables[0];
        
    }

    public DataTable executeSelect(String sql)
    {
        conn = OpenConnection();
        ds = new DataSet();
        da = new SqlDataAdapter(sql, conn);
        da.SelectCommand.CommandType = CommandType.StoredProcedure;

        da.Fill(ds);

        CloseConnection(conn);
        return ds.Tables[0];
    }
}
